﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
namespace System.Drawing
{
    public static class ImageExtension
    {
        public static Image GetThumbnailImage(this Image originalImage, int targetWidth)
        {   
            if (originalImage == null)
            {
                return null;
            }
            int height = originalImage.Height;
            int width = originalImage.Width;
            int maxWidthOrHeight = Math.Max(height, width);
            if (maxWidthOrHeight > targetWidth)
            {
                int proportion = maxWidthOrHeight / targetWidth;
                int newWidth = width / proportion;
                int newHeight = height / proportion;
                return originalImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
            }
            else
            {
                return originalImage;
            }
        }
        public static Image ToImage(this byte[] buffer, bool isReturnDefaultCard = true,string defaultImagePath="")
        {
            Image img = null;
            try
            {
                if (buffer != null)
                {
                    using (Stream stream = new MemoryStream(buffer))
                    {
                        img = Image.FromStream(stream);
                    }
                }
                else
                {
                    if (isReturnDefaultCard)
                    {
                        img = Image.FromFile(defaultImagePath);
                    }
                }
            }
            catch
            {
                if (isReturnDefaultCard)
                {
                    img = Image.FromFile(defaultImagePath);
                }
            }
            return img;
        }
        public static byte[] ToBinary(this Image imgage)
        {
            if (imgage == null)
            {
                return null;
            }
            var stream = new MemoryStream();
            try
            {
                imgage.Save(stream, ImageFormat.Jpeg);
                return stream.ToArray();
            }
            finally
            {
                stream.Close();
            }
        }
    }
}
